// 从URL中提取device_id参数
function getDeviceIdFromUrl() {
  // 匹配类似 /video/001 或 /001 的路径
  const pathname = window.location.pathname;
  const matches = pathname.match(/\/(download\/)?([^\/]+)$/);
  
  if (matches && matches[2]) {
    return matches[2];
  }
  
  return null;
}

// 设备信息收集
function getDeviceInfo() {
  const ua = navigator.userAgent;
  let deviceModel = '未知';
  let osVersion = '未知';
  let browserInfo = '未知';
  
  // 检测设备型号
  if (/iPhone|iPad|iPod/i.test(ua)) {
    const matches = ua.match(/(iPhone|iPad|iPod); CPU (iPhone )?OS (\d+)_(\d+)/i);
    if (matches && matches.length > 3) {
      deviceModel = `${matches[1]} ${matches[3]}`;
      osVersion = `iOS ${matches[3]}.${matches[4]}`;
    }
  } else if (/Android/i.test(ua)) {
    const matches = ua.match(/Android (\d+(\.\d+)?);\s+([^;]+)/i);
    if (matches && matches.length > 3) {
      osVersion = `Android ${matches[1]}`;
      deviceModel = matches[3].trim();
    }
  }
  
  // 检测浏览器
  if (/MicroMessenger/i.test(ua)) {
    const matches = ua.match(/MicroMessenger\/(\d+\.\d+)/i);
    browserInfo = `微信 ${matches ? matches[1] : '未知'}`;
  } else if (/Chrome/i.test(ua)) {
    const matches = ua.match(/Chrome\/(\d+\.\d+)/i);
    browserInfo = `Chrome ${matches ? matches[1] : '未知'}`;
  } else if (/Safari/i.test(ua)) {
    const matches = ua.match(/Version\/(\d+\.\d+).*Safari/);
    browserInfo = `Safari ${matches ? matches[1] : '未知'}`;
  }
  
  return {
    deviceModel,
    osVersion,
    browserInfo,
    screenResolution: `${window.screen.width}x${window.screen.height}`,
    language: navigator.language || navigator.userLanguage
  };
}

// API 配置
const deviceId = getDeviceIdFromUrl();
console.log(deviceId)
// const deviceId = 1;
if (!deviceId) {
  alert('未获取到设备ID，请检查访问链接');
  throw new Error('Missing device_id parameter');
}

let deviceInfo = null;
let userIp = '未知';

const API_CONFIG = {
  baseUrl: '/api/v1/m',
  endpoints: {
    userInfo: '/account/info',
    videoInfo: '/material/video/info',
    uploadConfirm: '/material/video/submit',
    changeVideo: '/material/video/change',
    publishedVideos: '/video/published'
  },
  // 设备ID作为全局参数
  phone_id: deviceId
};

// 全局变量
let currentVideoId = null;
let currentCoverUrl = null;
let isVideoPlaying = false;
let videoTags = '';

$(document).ready(function() {
  const domain = window.location.hostname;
  API_CONFIG.baseUrl = 'https://' + domain + '/api/v1/m';

  // 收集设备信息
  deviceInfo = getDeviceInfo();
  // $('#device-model').text(deviceInfo.deviceModel);
  $('#os-version').text(deviceInfo.osVersion);
  
  // 获取IP地址
  showLoading(true, '获取设备信息...');
  loadPageContent();
  
  // 为"已发布视频"按钮添加点击事件
  $('#published-videos-btn').click(function() {
    navigateToPublishedVideos();
  });
  
  // 为"复制话题"按钮添加点击事件
  $('#copy-tags-btn').click(function() {
    copyTagsToClipboard();
  });
  
  // 为"下载视频"按钮添加点击事件
  $('#download-video-btn').click(function() {
    downloadVideoDirectly();
  });
});

// 加载页面内容
function loadPageContent() {
  // 微信环境检测
  const isWeChat = /MicroMessenger/i.test(navigator.userAgent);
  if (isWeChat) {
    // 微信内特殊处理
    document.body.classList.add('wechat-env');
  }
  
  
  // 获取用户信息
  fetchUserInfo()
    .then(response => {
      if (response.code === 200) {
        payload = response.payload;
        $('#account').text(payload.account_name || '-');
        $('#phoneAlias').text(payload.phone_alias || '-');
        $('#phoneIp').text(payload.phone_ip || '-');
        fetchVideoInfo();
        showLoading(false)
      } else {
        showLoading(false);
        showToast(response.message, 'error');
        showLoading(true, response.message);
        console.error('获取视频失败:', response);
        return;
      }
    })
    .catch(error => {
      showToast('加载失败: ' + error.message, 'error');
      console.error('获取数据失败:', error);
    });

  // 视频封面点击事件
  $('#video-placeholder').click(function() {
    playVideo();
  });

  // 视频播放器点击事件（全屏处理）
  $('#video-player').click(function(e) {
    // 如果点击的是控制栏，不处理
    if (e.target.classList.contains('controls') || e.target.closest('.controls')) {
      return;
    }
    
    // 非控制栏点击，切换全屏
    toggleFullScreen();
  });

  // 为“我已发布”按钮添加点击事件
  $('#upload-btn').click(function() {
    if (!currentVideoId) {
      showToast('视频信息加载中，请稍后再试', 'warning');
      return;
    }
    
    showLoading(true, '正在提交...');
    
    // 调用API通知后端
    confirmUploadToServer()
      .then(response => {
        if (response.code === 200) {
          showToast('发布成功！', 'success');
          setTimeout(reloadPage, 1500);
        } else {
          showLoading(false);
          showToast(response.message, 'error');
          console.error('发布失败:', response);
        }
      })
      .catch(error => {
        showLoading(false);
        showToast('发布失败: ' + error.message, 'error');
        console.error('发布失败:', error);
      });
  });

  // 为“换一个”按钮添加点击事件
  $('#change-btn').click(function() {
    if (!currentVideoId) {
      showToast('视频信息加载中，请稍后再试', 'warning');
      return;
    }
    
    showLoading(true, '正在更换...');
    
    // 调用API更换视频
    changeVideo()
      .then(response => {
        if (response.code === 200) {
          showLoading(false);
          showToast('更换成功', 'success');
          fetchVideoInfo();
        } else {
          showLoading(false);
          showToast(response.message, 'error');
          console.error('更换视频失败:', response);
        }
      })
      .catch(error => {
        showLoading(false);
        showToast('更换视频失败: ' + error.message, 'error');
        console.error('更换视频失败:', error);
      });
  });
}

// 导航到已发布视频页面
function navigateToPublishedVideos() {
  // 获取当前设备ID
  const deviceId = API_CONFIG.deviceId;
  
  // 构建已发布视频页面URL，携带device_id参数
  const publishedVideosUrl = `/published-videos?device_id=${deviceId}`;
  
  // 跳转到新页面
  window.location.href = publishedVideosUrl;
}

// 复制话题到剪贴板
function copyTagsToClipboard() {
  if (!videoTags) {
    showToast('暂无话题，无法复制', 'warning');
    return;
  }
  
  // 创建临时文本区域
  const textarea = document.createElement('textarea');
  textarea.value = videoTags;
  textarea.style.position = 'fixed';
  textarea.style.opacity = '0';
  document.body.appendChild(textarea);
  
  // 选中并复制文本
  textarea.select();
  document.execCommand('copy');
  
  // 移除临时文本区域
  document.body.removeChild(textarea);
  
  // 显示成功提示
  showToast('话题已复制到剪贴板', 'success');
}

// 直接通过页面视频地址下载
function downloadVideoDirectly() {
  const videoSource = $('#video-source').attr('src');
  const videoFilename = $('#video-filename').text();
  
  if (!videoSource || videoSource === '' || videoSource === '-') {
    showToast('视频信息加载中，请稍后再试', 'warning');
    return;
  }
  
  showLoading(true, '准备下载...');
  
  // 检测浏览器类型
  const isChrome = /Chrome/i.test(navigator.userAgent);
  const isFirefox = /Firefox/i.test(navigator.userAgent);
  const isSafari = /Safari/i.test(navigator.userAgent) && !/Chrome/i.test(navigator.userAgent);
  const isMobile = /Mobile/i.test(navigator.userAgent);
  
  // 处理iOS Safari特殊情况
  if (isSafari && isMobile) {
    // iOS Safari不支持download属性，打开新窗口
    showLoading(false);
    // window.open(videoSource, '_blank');
    // showToast('请使用"共享"按钮保存视频', 'info');
    downloadVideo(videoSource, videoFilename);
    return;
  }
  
  // 现代浏览器支持download属性
  const a = document.createElement('a');
  a.href = videoSource;
  a.download = videoFilename || `video_${Date.now()}.mp4`;
  a.style.display = 'none';
  
  document.body.appendChild(a);
  
  // 尝试触发下载
  try {
    a.click();
  } catch (error) {
    console.error('下载失败:', error);
    
    // 失败时尝试其他方法
    if (isFirefox) {
      // Firefox可能需要使用location.href
      showLoading(false);
      window.location.href = videoSource;
      showToast('视频下载已开始', 'success');
      return;
    }
    
    // 其他浏览器尝试打开新窗口
    showLoading(false);
    window.open(videoSource, '_blank');
    showToast('请使用浏览器的下载功能保存视频', 'info');
    return;
  }
  
  // 清理
  setTimeout(() => {
    document.body.removeChild(a);
    showLoading(false);
    showToast('视频下载已开始，请在下载列表中查看', 'success');
  }, 500);
}

/**
 * 下载视频函数
 * @param {string} url - 视频URL
 * @param {string} fileName - 保存的文件名
 * @returns {Promise} - 下载操作的Promise
*/
function downloadVideo(url, fileName) {
  return new Promise((resolve, reject) => {
    // 检查浏览器是否支持下载功能
    if (!('download' in document.createElement('a'))) {
      reject(new Error('当前浏览器不支持下载功能，请使用现代浏览器'));
      return;
    }
    
    // 创建XHR对象获取视频数据
    const xhr = new XMLHttpRequest();
    xhr.open('GET', url, true);
    xhr.responseType = 'blob';
    
    xhr.onload = function() {
      if (xhr.status === 200) {
        // 获取视频Blob数据
        const blob = xhr.response;
        
        // 创建下载链接
        const url = URL.createObjectURL(blob);
        const a = document.createElement('a');
        a.href = url;
        a.download = fileName;
        a.click();
        
        // 释放URL对象
        setTimeout(() => {
          URL.revokeObjectURL(url);
          resolve();
        }, 100);
      } else {
        reject(new Error(`下载失败，状态码: ${xhr.status}`));
      }
    };
    
    xhr.onerror = function() {
      reject(new Error('下载请求出错'));
    };
    
    // 发送请求
    xhr.send();
  });
}


// 创建包含设备信息的请求头
function createDeviceHeaders() {
  return {
    'X-Device-ID': API_CONFIG.deviceId,
    'X-Device-Model': deviceInfo.deviceModel,
    'X-OS-Version': deviceInfo.osVersion,
    'X-Browser': deviceInfo.browserInfo,
    //'X-User-IP': userIp,
    'X-Screen-Resolution': deviceInfo.screenResolution,
    'X-Language': deviceInfo.language
  };
}

// 播放视频
function playVideo() {
  if (isVideoPlaying) return;
  
  const cover = $('#video-placeholder');
  const player = $('#video-player');
  
  cover.addClass('hidden');
  player.removeClass('hidden');
  
  const videoElement = document.getElementById('video-player');
  videoElement.play().then(() => {
    isVideoPlaying = true;
  }).catch(error => {
    console.error('播放失败:', error);
    showToast('视频播放失败: ' + error.message, 'error');
    // 播放失败，恢复封面
    cover.removeClass('hidden');
    player.addClass('hidden');
    isVideoPlaying = false;
  });
}

// 全屏播放视频
function toggleFullScreen() {
  const videoElement = document.getElementById('video-player');
  
  if (!document.fullscreenElement) {
    if (videoElement.requestFullscreen) {
      videoElement.requestFullscreen();
    } else if (videoElement.mozRequestFullScreen) { // Firefox
      videoElement.mozRequestFullScreen();
    } else if (videoElement.webkitRequestFullscreen) { // Chrome, Safari
      videoElement.webkitRequestFullscreen();
    } else if (videoElement.msRequestFullscreen) { // IE/Edge
      videoElement.msRequestFullscreen();
    }
  } else {
    if (document.exitFullscreen) {
      document.exitFullscreen();
    } else if (document.mozCancelFullScreen) {
      document.mozCancelFullScreen();
    } else if (document.webkitExitFullscreen) {
      document.webkitExitFullscreen();
    } else if (document.msExitFullscreen) {
      document.msExitFullscreen();
    }
  }
}

// 获取用户信息
function fetchUserInfo() {
  console.log(API_CONFIG.baseUrl + API_CONFIG.endpoints.userInfo);
  return $.ajax({
    url: API_CONFIG.baseUrl + API_CONFIG.endpoints.userInfo,
    method: 'GET',
    headers: createDeviceHeaders(),
    data: { phone_id: API_CONFIG.phone_id },
    dataType: 'json'
  });
}

// 获取视频信息
function fetchVideoInfo() {
  return $.ajax({
    url: API_CONFIG.baseUrl + API_CONFIG.endpoints.videoInfo,
    method: 'GET',
    headers: createDeviceHeaders(),
    data: { phone_id: API_CONFIG.phone_id },
    dataType: 'json'
  }).then(response => {
    response = response.payload;
    currentVideoId = response.video_id;
    currentCoverUrl = response.cover_url;
    
    // 更新视频封面
    const coverImg = $('#video-cover');
    if (response.cover_url) {
      coverImg.attr('src', response.cover_url);
      coverImg.attr('alt', response.title || '视频封面');
    }
    
    // 更新视频源
    const videoSource = $('#video-source');
    if (response.video_url) {
      videoSource.attr('src', response.video_url);
      document.getElementById('video-player').load();
    }
    
    // 更新视频文件名
    const videoFilename = $('#video-filename');
    if (response.filename) {
      videoFilename.text(response.filename);
    }
    
    // 更新话题标签
    const videoTagsElement = $('#video-tags');

    videoTags = '';
    videoTagsElement.text('暂无话题');
    if (response.tags && response.tags.length > 0) {
      videoTags = response.tags.join(' ');
      if (videoTags !== '') {
        videoTagsElement.text(videoTags);
      }
    }
    return response;
  });
}

// 通知服务器已上传
function confirmUploadToServer() {
  if (!currentVideoId) {
    return Promise.reject(new Error('没有当前视频ID'));
  }
  
  return $.ajax({
    url: API_CONFIG.baseUrl + API_CONFIG.endpoints.uploadConfirm,
    method: 'POST',
    headers: createDeviceHeaders(),
    data: JSON.stringify({ 
      video_id: currentVideoId,
      phone_id: API_CONFIG.phone_id
    }),
    contentType: 'application/json',
    dataType: 'json'
  });
}

// 更换视频
function changeVideo() {
  return $.ajax({
    url: API_CONFIG.baseUrl + API_CONFIG.endpoints.changeVideo,
    method: 'POST',
    headers: createDeviceHeaders(),
    data: JSON.stringify({ 
      video_id: currentVideoId,
      phone_id: API_CONFIG.phone_id
    }),
    contentType: 'application/json',
    dataType: 'json'
  }).then(response => {
    return response;
  });
}

// 显示/隐藏加载状态
function showLoading(show, text = '加载中...') {
  const loadingOverlay = $('#loading-overlay');
  const loadingText = $('#loading-text');
  
  loadingText.text(text);
  
  if (show) {
    console.log('showLoading 状态 true', show, text);
    loadingOverlay.removeClass('hidden');
    // 添加淡入动画
    setTimeout(() => {
      loadingOverlay.find('> div').addClass('scale-100 opacity-100');
    }, 10);
  } else {
    console.log('showLoading 状态 false', show, text);
    loadingOverlay.find('> div').removeClass('scale-100 opacity-100');
    setTimeout(() => {
      loadingOverlay.addClass('hidden');
    }, 300);
  }
}

// 显示提示消息
function showToast(message, type = 'success') {
  const toast = $('#toast');
  const toastIcon = $('#toast-icon');
  const toastMessage = $('#toast-message');
  
  // 设置图标和颜色
  if (type === 'success') {
    toastIcon.removeClass('fa-exclamation-circle fa-times-circle').addClass('fa-check-circle');
    toast.removeClass('bg-red-500 bg-yellow-500').addClass('bg-green-500');
  } else if (type === 'error') {
    toastIcon.removeClass('fa-check-circle fa-exclamation-circle').addClass('fa-times-circle');
    toast.removeClass('bg-green-500 bg-yellow-500').addClass('bg-red-500');
  } else if (type === 'warning') {
    toastIcon.removeClass('fa-check-circle fa-times-circle').addClass('fa-exclamation-circle');
    toast.removeClass('bg-green-500 bg-red-500').addClass('bg-yellow-500');
  }
  
  toastMessage.text(message);
  
  // 显示提示
  toast.removeClass('opacity-0').addClass('opacity-100');
  
  // 3秒后隐藏
  setTimeout(() => {
    toast.removeClass('opacity-100').addClass('opacity-0');
  }, 3000);
}

// 重新加载页面
function reloadPage() {
  location.reload();
}
    